#include "collectdatasave.h"
#include <QCoreApplication>
#include <QSettings>
#include <QDebug>
#include <QTextCodec>
#include <QDateTime>
#include <QtMath>
#include "filereadutil.h"


CollectDataSave::CollectDataSave(QObject *parent) : QObject(parent)
{



}

void CollectDataSave::inits(){
    configpath = QCoreApplication::applicationDirPath() + "/config/DataSaveConfig.ini";
    this->readconfig();
     resetDate();
     this->initview();
     this->contDatas();
}

QList<QObject*> CollectDataSave::getIitems(){
    return items;
}
///
/// \brief CollectDataSave::resetDate
/// 重置日期
///
void CollectDataSave::resetDate(){
    //6小时前的时间 6*60*60 ; 每天单时间为早上6点，
    QDateTime curDateTime=QDateTime::currentDateTime();
             curDateTime=curDateTime.addSecs(-21600);
    this->Datestr=curDateTime.toString("yyyyMMdd");

}
void CollectDataSave::nextid(){
    this->currid++;
}
void CollectDataSave::nextNumber(){
    this->sampleNuber++;
}

///
/// \brief CollectDataSave::contDatas
///统计当前的结果
void CollectDataSave::contDatas(){
    if(!lastData)
        return;


     QString path(savepath);
     path.append("/").append(ItemType).append(lastData->sample).append(".txt");
     QStringList items = FileReadUtil::readFile(path);

    QList<ItemData*> tempitems;
    double toto=0;
    qDebug()<< items.size();
    foreach(QString item ,items){
        ItemData * did=new ItemData;
        did->setJsonString(item);
        toto+=did->value;
    }
    double pto=toto/items.length();

    QString msg =QString("样本：%1 编号：%2 共测验：%3 次  均值：%4 ");


    if(lastData)
        msg=msg.arg(lastData->sample,QString::number(lastData->number),QString::number(items.length()),QString::number(pto,'f',precision));

    emit showDatas(msg);
}

////
/// \brief CollectDataSave::save
///点击界面上的保存按钮 事件
void CollectDataSave::save(){

    //qDebug()<<"save data: "<< QString::number( this->Value,'f');
    //先检测是否合极
    if(this->Value<=0){
        emit changMessage("输入值 "+ QString::number( this->Value,'f',precision) +"无效值");
        return ;
    }

    itemindex++;

    this->saveDatas();

    this->Value=0;

    this->nextid();

    writeconfig();

    contDatas();

    emit valuechang();
}

///
/// \brief CollectDataSave::saveDatas
///保存当前的记录到到文件中
///
void CollectDataSave::saveDatas(){
    ItemData * data =new ItemData(this);
    data->id=this->currid;
    data->itemname=this->ItemType;
    data->product=this->product;
    data->value=this->Value;
    data->number=this->sampleNuber;
    data->precision=this->precision;
    data->index=itemindex;
    data->tolerance=this->Value;

    data->sample=QString().append(product).append(QString::number(sampleNuber)).append(Datestr);


    this->islrance=false;
    data->istolerance=false;

    //计算二项差
    if(items.length()>0){
        ItemData* item= (ItemData*)items.value(0);
        if(item->number==this->sampleNuber){
            double ter =fabs(this->Value-item->value);
            data->tolerance=ter;
            if(ter <= this->tolerance){
                data->istolerance=true;
                this->islrance=true;
            }
        }
    }

    lastData=data;
    items.insert(0,data);

    QString path(savepath);
    path.append("/").append(ItemType).append(data->sample).append(".txt");
    dataTool.appendFile(path,data->jsonString());

}

///
/// \brief CollectDataSave::next
///点击界面上的下一项 触发事件
///
void CollectDataSave::next(){

    if(this->itemindex<2){
        emit changMessage("每个样品最少需要测试两次以上");
        return;
    }

    if(!this->islrance ){
        ItemData* item= (ItemData*)items.value(0);
        emit changMessage("连续二次测验值差"+ QString::number( item->tolerance,'f',precision) +"不在"+ QString::number( this->tolerance,'f',precision) +"范围内,需要重新测.");
        return ;
    }

    this->islrance=false;

    this->itemindex=0;

    this->nextNumber();
    this->resetDate();

    writeconfig();

    emit valuechang();

}
void  CollectDataSave::selectNumber(int num){
    qDebug()<<"select:" <<num;
}

///
/// \brief CollectDataSave::chengvalue
///配置项发生改变
///
void CollectDataSave::chengvalue(){
    this->writeconfig();
}

///
/// \brief CollectDataSave::readconfig
///读取配置项目
void CollectDataSave::readconfig(){
    QSettings * set = new QSettings(configpath, QSettings::IniFormat);
    set->setIniCodec(QTextCodec::codecForName("UTF-8"));
    QVariant qid = set->value(QString("/%1/%2").arg("INFO").arg("currid"));
    currid =qid.toInt();

    QVariant itemtype = set->value(QString("/%1/%2").arg("INFO").arg("itemtype"));
    this->ItemType=itemtype.toString();

    QVariant product = set->value(QString("/%1/%2").arg("INFO").arg("product"));
    this->product=product.toString();

    QVariant number = set->value(QString("/%1/%2").arg("INFO").arg("sampleNuber"));
    this->sampleNuber=number.toInt();

    QVariant tolerance = set->value(QString("/%1/%2").arg("INFO").arg("tolerance"));
    this->tolerance=tolerance.toDouble();

    QVariant precision = set->value(QString("/%1/%2").arg("INFO").arg("precision"));
    this->precision=precision.toInt();

    QVariant savepath = set->value(QString("/%1/%2").arg("INFO").arg("savepath"));
    this->savepath=savepath.toString();

    QVariant vprecision = set->value(QString("/%1/%2").arg("INFO").arg("delivery"));
    this->delivery=vprecision.toInt();

    //qDebug()<< vprecision.toString();
}

///
/// \brief CollectDataSave::initview
///初始化 回读最后一条记录记录，当关闭应用时，再打开可以继续工作
///
void  CollectDataSave::initview(){
    QString path(savepath);
    path.append("/").append(ItemType).append(product).append(QString::number(sampleNuber)).append(Datestr).append(".txt");
    QStringList gitems= FileReadUtil::readFile(path);

    foreach(QString item ,gitems){
        ItemData * did=new ItemData;
        did->setJsonString(item);
        items.insert(0,did);
        lastData =did;
        islrance=did->istolerance;
        itemindex++;
    }
}


///
/// \brief CollectDataSave::writeconfig
///当前配置变化写入到配置文件中，在下次打开界面时还能到最新的配置上
///
void CollectDataSave::writeconfig(){
    QSettings * set = new QSettings(configpath, QSettings::IniFormat);
    set->setIniCodec(QTextCodec::codecForName("UTF-8"));
    set->setValue(QString("/%1/%2").arg("INFO").arg("currid"),QVariant(this->currid));
    // set->setValue(QString("/%1/%2").arg("INFO").arg("itemtype"),QVariant(this->ItemType));
    // set->setValue(QString("/%1/%2").arg("INFO").arg("product"),QVariant(this->product));
    set->setValue(QString("/%1/%2").arg("INFO").arg("sampleNuber"),QVariant(this->sampleNuber));
    // set->setValue(QString("/%1/%2").arg("INFO").arg("tolerance"),QVariant(this->tolerance));
    // set->setValue(QString("/%1/%2").arg("INFO").arg("precision"),QVariant(this->precision));
    // set->setValue(QString("/%1/%2").arg("INFO").arg("savepath"),QVariant(this->savepath));


}
